package com.ktjy.car.interceptor;

import com.ktjy.car.entity.Login;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 放行登录接口和修改密码接口
        if (request.getRequestURI().contains("/login")) {
            return true;
        }

        // 获取token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String redisKey = "token:" + token;
            
            // 修改验证逻辑
            Object obj = redisTemplate.opsForValue().get(redisKey);
            if (obj != null) {  // 只要token存在且有效即可
                redisTemplate.expire(redisKey, 1, TimeUnit.HOURS);
                return true;
            }
        }
        
        // 设置跨域响应头
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
}